<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Auction extends Admin_Controller {
	protected $list_view_order_name = 'end_time';
	protected $list_view_order_direction = 'DESC';
	protected $list_view_pagination = array(20,50,100);
	protected $list_view_searched_fields = array(
			'title'			=>	'Title',
		);
	protected $fields =  array(
				'status'			=>	array(
											'text'	=>	'Status',
											'type'	=>	'checkbox',
											'form_view'=>array()
										),
				'title'				=>	array(
											'text'	=>	'Title',
											'type'	=>	'text',
											'list_view'=>array(
												'is_show_link'	=>	true
											),
											'form_view'=>array(
												'validate_type'	=>	'required : true'
											)
										),
				/*'price'				=>	array(
											'text'	=>	'Price (USD)',
											'type'	=>	'text',
											'list_view'=>array(
												'is_show_link'	=>	true
											),
											'form_view'=>array(
												'validate_type'	=>	'required : true'
											)
										),*/
				'price_vn'				=>	array(
											'text'	=>	'Price (VND)',
											'type'	=>	'text',
											'list_view'=>array(
												'is_show_link'	=>	true
											),
											'form_view'=>array(
												'validate_type'	=>	'required : true'
											)
										),
				'description'		=>	array(
										'text'	=>	'Description',
										'type'	=>	'textarea',
										'form_view'=>array(
											'editor'	=>	true
										)
									),
				'image_small'		=>	array(
										'text'	=>	'Image (160x146)',
										'type'	=>	'file',
										'file_config' => array(
											'file_type' => 'image',
											'file_height' => 146,
											'file_dir_path' => 'uploads/auction/image/160x146/'
										),
										'list_view'=>array(
											'width' => 100,
											'file_height' => 73,
											'is_show_link'	=>	true
										),
										'form_view' => array(
										)
									),
				'image_large'		=>	array(
										'text'	=>	'Image (323x213)',
										'type'	=>	'file',
										'file_config' => array(
											'file_type' => 'image',
											'file_height' => 213,
											'file_dir_path' => 'uploads/auction/image/323x213/'
										),
										'form_view' => array(
										)
									),
				'end_time'		=>	array(
										'text'		=>	'End time',
										'type'		=>	'text',
										'datetime_type' => 'datetime',
										'list_view'	=>array(
											'is_show_link'	=>	true
										),
										'form_view'=>array(
											'type'	=>	'text',
											'func'	=>	'datetime'
										)
									),
				
				// Not allow to change is_ended by admin
				/*
				'is_ended'		=>	array(
										'text'	=>	'Is ended',
										'type'	=>	'checkbox',
										'form_view'=>array(),
										'list_view'	=>array(
											'is_show_link'	=>	true
										),
									),*/
		);

	/** End: Config **/

	/*------------------------------------ Admin Control Panel ------------------------------------*/
	
	protected function after_save($obj_id){
		// Do cron tab
		$this->_do_crontab();
	}
	function _do_crontab(){
		try {
			$data = array();
			$now = getNow();
			$auction_list = $this->model->fetch('*','tb_auction',"status = 1 AND end_time > '{$now}'",'end_time','desc',-1,0,true);//last_query(1);
			$data['auction_list'] = $auction_list;
			$crontab_file_content = $this->load->view('BACKEND/crontab',$data,true);
			$file_path = BASEFOLDER.'cron/crontab.txt';
			file_put_contents($file_path,$crontab_file_content);
			shell_exec('sudo crontab '.$file_path);
		} catch (Exception $e) {
			
		}
	}
	/*----------------------------- End Admin Control Panel --------------------------------*/

	
	
	
	
	/*------------------------------------ FRONTEND ------------------------------------*/	
	/*function stop_auction_old($auction_id=0,$action=''){
		$auction_id = (int)$auction_id;
		if(!empty($auction_id)){
			$auction = $this->model->get('*','tb_auction',"id = {$auction_id}",true);
			if(!empty($auction)){
				$auction['is_ended'] = 1;
				
				// Get unique and smallest value
				$query = "SELECT *
						FROM tb_auction_bid
						WHERE auction_id = {$auction_id}
						GROUP BY value
						HAVING COUNT(*) = 1
						ORDER BY value ASC
						LIMIT 1
						";
				$query = $this->db->query($query);
				$bid = $query->row_array();
				
				if(empty($bid)){
					$query = "SELECT * 
						FROM tb_auction_bid
						WHERE auction_id = {$auction_id}
						ORDER BY value DESC, id ASC
						LIMIT 1
						";
					$query = $this->db->query($query);
					$bid = $query->row_array();
				}
				
				if(!empty($bid)){
					$user = $this->model->get('*',ADMIN_USER_TABLE,"id = {$bid['user_id']}",true);
					if(!empty($user)){
						if($action=='temporary_update'){ // For Websocket
							$result['user_email'] = $user['email'];
							$result['winner_price_vn'] = number_format($bid['value']*1000, 0, ',', '.');
							echo json_encode($result);
						} else { // Final update triggerd by countdown timer
							// Update winning bid
							$bid['is_won'] = 1;
							$this->model->update('tb_auction_bid',$bid,"id = {$bid['id']}");
							
							// Update auction
							$auction['winner'] = $user['email'];
							$auction['winner_id'] = $user['id'];
							$auction['winner_price_vn'] = $bid['value']*1000;
							
							if($this->model->update('tb_auction',$auction,"id = {$auction_id}")){
								echo 'Stop auction successfully!';
							}
						}
					}
				}
			}
		}
	}*/
	
	function stop_auction($auction_id=0,$action=''){
		$auction_id = (int)$auction_id;
		if(!empty($auction_id)){
			$auction = $this->model->get('*','tb_auction',"id = {$auction_id}",true);
			if(!empty($auction)){
				$auction['is_ended'] = 1;
				
				$query = "SELECT *
						FROM tb_auction_bid
						WHERE auction_id = {$auction_id}
						";
				$query = $this->db->query($query);
				$bid_list = $query->result_array();
				$smallest_value = 0;
				$unique_smallest_value_bid_mapping = array();
				$largest_earliest_value_bid_mapping = array();
				$not_unique_value = array();
				$max_value = 0;
				foreach($bid_list as &$bid){
					$bid_value = decrypt($bid['value_encrypted'],ENCRYPTION_KEY_PASSWORD);
					$bid['value'] = $bid_value;
					if(!in_array($bid_value, $not_unique_value)){
						if(empty($unique_smallest_value_bid_mapping[$bid_value])){
							$unique_smallest_value_bid_mapping[$bid_value] = $bid;
						} else {
							unset($unique_smallest_value_bid_mapping[$bid_value]);
							$not_unique_value[] = $bid_value;
						}
					}
					
					// In addition: Get max bid value
					if($max_value==0 || $max_value < $bid_value){
						$max_value = $bid_value;
						$largest_earliest_value_bid_mapping = array(); // Make array empty
						$largest_earliest_value_bid_mapping[$max_value] = $bid;
					} else if($bid_value == $max_value){
						$current_earliest_bid = $largest_earliest_value_bid_mapping[$max_value];
						if($bid['id'] < $current_earliest_bid['id']){
							$largest_earliest_value_bid_mapping[$max_value] = $bid;
						}
					}
				}
				$won_mapping = !empty($unique_smallest_value_bid_mapping) ? $unique_smallest_value_bid_mapping : $largest_earliest_value_bid_mapping;
				if(!empty($won_mapping)){
					asort($won_mapping); // If $unique_smallest_value_bid_mapping is selected
					foreach($won_mapping as $bid_value=>$bid){
						$won_bid = $bid;
						break;
					}
				}
				
				if(!empty($won_bid)){
					$user = $this->model->get('*',ADMIN_USER_TABLE,"id = {$won_bid['user_id']}",true);
					$won_bid_value = $won_bid['value'];
					unset($won_bid['value']);
					if(!empty($user)){
						if($action=='temporary_update'){ // For Websocket
							$result['user_email'] = $user['email'];
							$result['winner_price_vn'] = number_format($won_bid_value*1000, 0, ',', '.');
							echo json_encode($result);
						} else { // Final update triggerd by countdown timer
							$return_result = true;
							
							// Update winning bid
							$won_bid['is_won'] = 1;
							$this->model->update('tb_auction_bid',$won_bid,"id = {$won_bid['id']}");
							
							// Update auction
							$auction['winner'] = $user['email'];
							$auction['winner_id'] = $user['id'];
							$auction['winner_price_vn'] = $won_bid_value*1000;
							
							if($this->model->update('tb_auction',$auction,"id = {$auction_id}")){
								// Begin: Return coins for loosers
								// Rule: Người có số lần đặt giá nhiều nhất trong 1 phiên đấu giá nhưng không thắng sẽ được hoàn lại 50% số tiền ảo đã đặt
								$return_coins_result = true;
								$query = "SELECT user_id, is_refund, COUNT(*) AS coin_count
										FROM tb_auction_bid
										WHERE auction_id = {$auction_id}
										GROUP BY user_id
										ORDER BY coin_count DESC
										";
								$query = $this->db->query($query);
								$lost_bid_list = $query->result_array();
								if(count($lost_bid_list) > 0){
									$max_coin_count = $lost_bid_list[0]['coin_count'];
									$max_half_coin_count = ceil($max_coin_count/2);
									foreach($lost_bid_list as $lost_bid){
										if(empty($lost_bid['is_refund']) && $lost_bid['coin_count'] == $max_coin_count && $lost_bid['user_id'] != $won_bid['user_id']){
											// Refund 50% coin count
											$sql = "UPDATE tb_user SET coin_number = coin_number + {$max_half_coin_count} WHERE id = {$lost_bid['user_id']}"; 
											if($this->db->query($sql)){
												$sql = "UPDATE tb_auction_bid SET is_refund = 1 WHERE user_id = {$lost_bid['user_id']}";
												if(!$this->db->query($sql)){
													$return_coins_result = false;
													break;
												}
											} else {
												$return_coins_result = false;
												break;
											}
										}
									}
								}
								$return_result = $return_result & $return_coins_result;
								// End: Return coins for loosers
								
								// Begin: Send mail to winner
								$to      = $user['email'];
								$subject = 'Thông báo thắng đấu giá';
								$end_time = date('d-m-Y H:i',strtotime($auction['end_time']));
								$message = "Xin chúc mừng người chơi với email là {$user['email']} đã thắng phiên đấu giá của sản phẩm \"{$auction['title']}\", kết thúc lúc {$end_time}.\r\n";
								$message .= "Vui lòng liên hệ Ban tổ chức để nhận sản phẩm.\r\n";
								$headers = 'From: kngan119411@yahoo.com' . "\r\n" .
									'Reply-To: kngan119411@yahoo.com' . "\r\n" .
									'X-Mailer: PHP/' . phpversion();

								mail($to, $subject, $message, $headers);
								// End: Send mail to winner
							} else {
								$return_result = false;
							}
							if($return_result){
								echo 'Stop auction successfully!';
							}
						}
					}
				}
			}
		}
	}
	
	function detail($auction_id=0){
		$auction_id = (int)$auction_id;
		if(!empty($auction_id)){
			$auction = $this->model->get('*','tb_auction',"id = {$auction_id}",true);
			if(!empty($auction)){
				$data['auction'] = $auction;
				$this->template->write_view('content','FRONTEND/detail',$data);
				$this->template->render();
			}
		}
	}
	function submit(){
		if(!empty($_SESSION['user'])){
			$user = $_SESSION['user'];
			$user_id = $user['id'];
			$auction_id = (int)$this->input->post('auction_id');
			$bid_value = (int)$this->input->post('bid_value');
			
			$value_encrypted = encrypt($bid_value,ENCRYPTION_KEY_PASSWORD);
			$value_md5 = md5($bid_value);
			// Check duplicate value
			$duplicate_bid = $this->model->get('id','tb_auction_bid',"auction_id = {$auction_id} AND user_id = {$user_id} AND value_md5 = '{$value_md5}' ",true);
			if(empty($duplicate_bid)){
				$user_data = $this->model->get('id,coin_number',ADMIN_USER_TABLE,"id = {$user_id}",true);
				if(!empty($user_data) && !empty($auction_id) && !empty($bid_value)){
					$coin_number = $user_data['coin_number'];
					$coin_number = $coin_number - 1; // TODO: If failed bid => return coins?
					if($coin_number >= 0){
						$user_data['coin_number'] = $coin_number;
						if($this->model->update(ADMIN_USER_TABLE,$user_data,"id = {$user_id}")){
							// Reupdate session
							$user['coin_number'] = $user_data['coin_number'];
							$_SESSION['user'] = $user;
							
							// Saving bid
							$auction_bid['auction_id'] = $auction_id;
							$auction_bid['user_id'] = $user['id'];
							// $auction_bid['value'] = $bid_value;
							$auction_bid['value_encrypted'] = $value_encrypted;
							$auction_bid['value_md5'] = $value_md5;
							$auction_bid['created'] = getNow();
							if($this->model->insert('tb_auction_bid',$auction_bid)){
								echo 'success';
							}
						}
					} else {
						echo 'Bạn đã hết xu';
					}
				}
			} else {
				echo 'Bạn đã đấu giá này rồi';
			}
		}
	}
	
	function result(){
		$return_data = array();
		$html = '';
		$winner_price = 0;
		$auction_id = (int)$this->input->post('auction_id');
		if(!empty($auction_id)){
			$auction = $this->model->get('*','tb_auction',"id = {$auction_id} AND is_ended = 1",true);
			if(!empty($auction)){
				$html = 'Thắng cuộc là<br/>'.$auction['winner'];
				$winner_price = number_format($auction['winner_price_vn'], 0, ',', '.');
			} else {
				$html = 'No winner';
			}
		}
		$return_data['html'] = $html;
		$return_data['winner_price'] = $winner_price;
		echo json_encode($return_data);
	}
	/*------------------------------------ End FRONTEND --------------------------------*/
}